﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using University.Workshop.Model;
using System.Text.RegularExpressions;
using University.Workshop.DataAccess;
using System.Globalization;

namespace University.Workshop.Business
{
    public static class UserPasswordUpdateManager
    {
        public static User UpdatePassword(
            String email, 
            String currentPass, 
            String newPass, 
            String retypePass
            )
        {
            if (string.IsNullOrEmpty(email) ||
                string.IsNullOrEmpty(currentPass) ||
                string.IsNullOrEmpty(newPass) ||
                string.IsNullOrEmpty(retypePass)
                )
            {
                throw new ValidationException("All fields are required");
            }

             User existingUser = UserDataAccess.UserExists(email,currentPass.GetHashCode().ToString(CultureInfo.InvariantCulture));
             if (existingUser == null)
             {
                 throw new BusinessException("YouR current password is incorrect");
             }

            string passwordPattern = "\\w{6,20}";
            string passwordPattern1 = "\\d+";
            if (!(Regex.IsMatch(newPass, passwordPattern) && Regex.IsMatch(newPass, passwordPattern1)))
            {
                throw new ValidationException("New Password Invalid");
            }
            if (newPass != retypePass)
            {
                throw new ValidationException("New Passwords do not match");
            }

            User newUser = new User();
            newUser.ContactInformation.Email = email;
            newUser.Password = currentPass;

            UserDataAccess.ChangeUserPassword(newUser,newPass);
            return newUser;
   
        }
    }
}
